// 试卷配置相关的组合式函数
import { ref, computed, onMounted } from 'vue'
import { useConfig } from './useConfig.js'

export function useExamConfig() {
  // 使用配置服务
  const {
    loadConfig,
    getGradeLevel,
    getKnowledgePointsBySubjectAndGrade,
    getDefaultConfig
  } = useConfig()

  // 响应式配置数据
  const config = ref({ ...getDefaultConfig() })

  // 在组件挂载时加载配置
  onMounted(async () => {
    try {
      await loadConfig()
      console.log('试卷配置初始化完成')
    } catch (error) {
      console.warn('配置加载失败，使用默认配置:', error)
    }
  })

  // 计算属性
  const canGenerate = computed(() => {
    return config.value.grade && 
           config.value.difficulty && 
           config.value.subject && 
           config.value.knowledgePoints.length > 0 &&
           hasEnabledQuestionTypes.value
  })

  const hasEnabledQuestionTypes = computed(() => {
    return Object.values(config.value.questionTypes).some(type => type.enabled && type.count > 0)
  })

  const examTitle = computed(() => {
    if (!config.value.grade || !config.value.subject) return ''
    return `${config.value.grade}${config.value.subject}测试卷`
  })

  // 方法
  const getKnowledgePoints = (subject) => {
    return getKnowledgePointsBySubjectAndGrade(subject, config.value.grade)
  }

  const updateKnowledgePoints = () => {
    config.value.knowledgePoints = []
  }

  const resetConfig = () => {
    config.value = { ...getDefaultConfig() }
  }

  const updateConfig = (newConfig) => {
    config.value = { ...config.value, ...newConfig }
  }

  return {
    config,
    canGenerate,
    hasEnabledQuestionTypes,
    examTitle,
    getGradeLevel,
    getKnowledgePoints,
    updateKnowledgePoints,
    resetConfig,
    updateConfig
  }
}